<?php

namespace App\Repositories;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

abstract class BaseRepository
{
    protected $model;

    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    /**
     * 获取所有记录
     */
    public function all(): Collection
    {
        return $this->model->all();
    }

    /**
     * 根据ID查找记录
     */
    public function find(int $id): ?Model
    {
        return $this->model->find($id);
    }

    /**
     * 根据条件查找记录
     */
    public function findBy(array $conditions): ?Model
    {
        return $this->model->where($conditions)->first();
    }

    /**
     * 根据条件查找多条记录
     */
    public function findWhere(array $conditions): Collection
    {
        return $this->model->where($conditions)->get();
    }

    /**
     * 创建记录
     */
    public function create(array $data): Model
    {
        return $this->model->create($data);
    }

    /**
     * 更新记录
     */
    public function update(int $id, array $data): bool
    {
        return $this->model->where('id', $id)->update($data);
    }

    /**
     * 删除记录
     */
    public function delete(int $id): bool
    {
        return $this->model->where('id', $id)->delete();
    }

    /**
     * 分页查询
     */
    public function paginate(int $perPage = 15): LengthAwarePaginator
    {
        return $this->model->paginate($perPage);
    }

    /**
     * 计数
     */
    public function count(array $conditions = []): int
    {
        if (empty($conditions)) {
            return $this->model->count();
        }
        return $this->model->where($conditions)->count();
    }

    /**
     * 检查记录是否存在
     */
    public function exists(array $conditions): bool
    {
        return $this->model->where($conditions)->exists();
    }
}
